/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
	AppRegistry,
	StyleSheet,
	Text,
	View,
	Image,
	TextInput,
	TouchableOpacity,
	ToolbarAndroid,
	Dimensions,
	Platform,
	BackHandler,
	ScrollView,
	Modal,
	Clipboard,
	DeviceEventEmitter,
	StatusBar,
	Keyboard,
	PermissionsAndroid,
	Alert,
	NativeModules
} from 'react-native';

import Toast from 'react-native-root-toast';
import Common from '../../component/common';
import ScreenUtils from '../../component/ScreenUtils';
import ToolbarComponent from '../../component/ToolbarComponent';
import SubscriptionItem from './part/subscriptionItem';

import CameraRollCom from './part/cameraRollCom';

const STATUS_BAR_HEIGHT = StatusBar.currentHeight || 20;


const totalWidth = Dimensions.get('window').width;
const HEADER_HEIGHT = totalWidth*0.112;

export default class feedBack extends Component {
	constructor(props) {
		super(props);
		this.state = {
			info: "",
			contactInfor: "",
			userToken: this.props.did,
			relaPics: null,
		};
		this.Imagestyle = {};
		this.relaPics = [];
		this.selectData = []
	}
	componentWillMount() {
		if(Platform.OS === 'android') {
			BackHandler.addEventListener('hardwareBackPress', () => Common.onBack(this));
		}
	}
	componentWillUnmount() {
		this.upLoadImage.remove();
		if(Platform.OS === 'android') {
			BackHandler.removeEventListener('hardwareBackPress', () => Common.onBack(this));
		}
	}
	componentDidMount() {
		this._setClipboardContent()
		this.upLoadImage = DeviceEventEmitter.addListener('upLoadImage', (data) => {

			this.setState({
				relaPics: JSON.parse(data),
			})
			this.relaPics = JSON.parse(data);
			this.selectData = JSON.parse(data);
			
		});
	}

	/*openByPicker() {
 	this.setState({openPersonAvatarImage:false});
  	let that = this;
  	this.relaPics=[];
  	MyImagePicker2.openPicker({
     width:100,
     height:100,
     multiple: true,
	}).then(images => {
		if(images.length>3 || this.relaPics.length>=3){
			Toast.show("最多只能上传三张图片", {
	            duration: Toast.durations.LONG,
	            position: Toast.positions.CENTER,
	            shadow: true,
	            animation: true,
	            hideOnPress: true,
	        	delay: 0
			});
		}else{
			for(let i=0;i<images.length;i++){
				this.relaPics.push(images[i]);
			}
			this.setState({
				relaPics:this.relaPics,
			});
		}
	}).catch( (e) =>{
		alert(e);
	});
  }*/

	_submitForm() {
		
		if(this.state.info.trim() == "") {

			Toast.show("您的意见对我们很重要，写点什么吧。", {
				duration: Toast.durations.LONG,
				position: Toast.positions.CENTER,
				shadow: true,
				animation: true,
				hideOnPress: true,
				delay: 0
			});
			return false;
		}
		let formData = new FormData();
		let files = []
		if(this.state.relaPics) {
			for(let i = 0; i < this.state.relaPics.length; i++) {
				let file = {"uri": this.state.relaPics[i].uri, "type": "multipart/form-data", "name": "image.png" };
				formData.append("relaPics",file);
			}
		} else {
			formData.append("relaPics", "");
		}
		
		formData.append("info",this.state.info);
		formData.append("contactInfor", this.state.contactInfor);
		
		let _that = this;
		Common.fetchData("POST", "/common/suggest", formData, (responseData) => {
			Toast.show("谢谢您的建议", {
				duration: Toast.durations.LONG,
				position: Toast.positions.CENTER,
				shadow: true,
				animation: true,
				hideOnPress: true,
				delay: 0
			});
			Common.onBack(_that);
		}, (responseData) => {
			if(responseData.size.isSize){
				Toast.show("反馈失败，请重新操作", {
					duration: Toast.durations.LONG,
					position: Toast.positions.CENTER,
					shadow: true,
					animation: true,
					hideOnPress: true,
					delay: 0
				});
			}else{
				Toast.show("图片不能超过2M", {
					duration: Toast.durations.LONG,
					position: Toast.positions.CENTER,
					shadow: true,
					animation: true,
					hideOnPress: true,
					delay: 0
				});				
			}
		}, () => {
			Toast.show("反馈失败，请重新操作", {
				duration: Toast.durations.LONG,
				position: Toast.positions.CENTER,
				shadow: true,
				animation: true,
				hideOnPress: true,
				delay: 0
			});
		});
	}

	async _setClipboardContent() {
		try {
			var content =await Clipboard.getString();
			Clipboard.setString(content);
		} catch(e) {
			this.setState({ content: e.message });
		}
	}
	handleDelete(index) {
		let arr = JSON.parse(JSON.stringify(this.state.relaPics));
		arr.splice(index, 1);
		this.setState({
			relaPics: arr,
		});
		this.relaPics = arr;
		this.selectData = arr;
	}
	
	async askPer() {
		Keyboard.dismiss();
		if(Platform.OS === 'android'){
		  let result = await PermissionsAndroid.check("android.permission.WRITE_EXTERNAL_STORAGE");
		  if(result){
		   Common.onForward(this, CameraRollCom, this.relaPics);
		  }else{

		  //  Toast.show("请到设置->应用->权限中打开SD卡读写权限", {
		  //   duration: Toast.durations.LONG,
		  //   position: Toast.positions.CENTER,
		  //   shadow: true,
		  //   animation: true,
		  //   hideOnPress: true,
		  //   delay: 0
		  //  })
			// this.setState({
			// 	showPerSetting:true,
			// })
			Common.userTip("请到权限管理中打开SD卡读写权限")
		  }

		}else{
			NativeModules.JsAndroid.camAuthStatus(
				(data)=>{
					if(data.album==true){
						Common.onForward(this, CameraRollCom, this.relaPics);
					}else{
					   Toast.show("请打开影响App的相册权限", {
					    duration: Toast.durations.LONG,
					    position: Toast.positions.CENTER,
					    shadow: true,
					    animation: true,
					    hideOnPress: true,
					    delay: 0
					   })

					}
				}
			)
			//Common.onForward(this, CameraRollCom, this.relaPics);
		}
	}
	handleForward() {
		this.relaPics = [];
		this.selectData.map((item, key) => {
			this.relaPics.push(item);
		})
		Keyboard.dismiss()
		Common.onForward(this, CameraRollCom, this.relaPics);
	}
	
	render() {

		return(
			<View style ={styles.feedBackContainer}>
		  	    <ToolbarComponent
		          leftItem={{
		            title: 'Back',
		            layout: 'icon',
		            icon: require("../../images/back.png"),
		            onPress: () => {
		              Common.onBack(this);
		            },
		          }}
		        >
		          	<View style={styles.toolbarV}>
		            	<Text style={styles.toolbarT} numberOfLines={1}>意见反馈</Text>
		          	</View>
		        </ToolbarComponent>
		      	<ScrollView
					contentContainerStyle={styles.feedBackWrap}
  					horizontal = {false}
					keyboardShouldPersistTaps="handled"
					keyboardDismissMode='interactive' 
					showsVerticalScrollIndicator ={false}
		      	>
		    			<View style={styles.feedBackFormWrap} >
		    				<View style={styles.userTipWrap}>
		    					<Text style={styles.userTip}>
		    						您好，欢迎反馈！反馈时请附上界面显示截屏，可以更便于我们查看问题哦~
		    					</Text>
		    				</View>
		    				<View style={styles.feedBackForm}>
		    		  			<View style={styles.inputAreaWrap}>
		    		  				<TextInput 
			    				  		underlineColorAndroid = "transparent"
			    				  		placeholderTextColor = "#d3d3d3"
			    				  		multiline = {true}
			    				  		numberOfLines = {10}
			    				  		textAlignVertical ="top"
			    				  		placeholder="请输入内容"
			    				  		onChangeText ={(info) => this.setState({info:info })}
			    				  		value ={this.state.info}
			    				  		style={styles.info}
			    				  		ref="content" />
			    		  			<View style={styles.relaPics}>
			    		  				<TouchableOpacity
			    		  					style={{width:ScreenUtils.scaleSize(80),}}
			    		  					onPress = {this.askPer.bind(this)}>
				    		  				<Image style={styles.relaPicsImage} source = {require("../../images/pic.png")}/>
				    		  				<Text style={{fontSize:ScreenUtils.scaleSize(18),color:"#ccc",paddingTop:ScreenUtils.scaleSize(5)}}>上传图片</Text>
			    		  				</TouchableOpacity>
			    		  			</View>
		    		  			</View>
		    					<TextInput
		    				        placeholder="请留下您的联系方式 如QQ_2345678"
		    				        placeholderTextColor ="#b8b8b8"
		    				        underlineColorAndroid = "transparent"
		    				        style ={styles.qqNum}
		    				        onChangeText ={(contactInfor) => this.setState({contactInfor:contactInfor})}
		    				  		value ={this.state.contactInfor}
		    				  		ref="qqNum"
		    				    />
		    					<Text style={styles.tip}>留下您的联系方式有助于我们沟通和解决问题,我们会严格保密</Text>
			    					{
			    						this.state.relaPics ?
			    						<View>
				    						<View style={styles.imageReview}>
					    						{
					    							this.state.relaPics.map((item,key)=>{
					    								return (
					    									<TouchableOpacity 
					    										key={key} 
					    										style={styles.relaPicsWrap}
					    										onPress = {this.handleForward.bind(this)}
					    									>
					    										<Image 
					    											style={[styles.relaPicsWrapImg,{borderWidth:1,borderColor:"#ededed"}]} 
					    											source={{uri:item.uri}}
					    										/>
					    										<TouchableOpacity 
					    											style={{
					    												width:20,
					    												height:20,
					    												position:'absolute',
					    												top:0,
					    												right:1,
					    												zIndex:999,
					    												borderRadius:10,
					    												backgroundColor:'#888'
					    											}}
					    											onPress = {this.handleDelete.bind(this,key)}
					    										>
					    											<View 
					    												style={{
					    													flex:1,
					    													justifyContent:"center",
					    													alignItems:"center",
					    												}}
					    											>
					    												<Text style={{fontSize:14,color:"#ededed",textAlign:"center"}}>&times;</Text>
					    											</View>
					    										</TouchableOpacity>
					    									</TouchableOpacity>
					    								)
					    							})
					    						}
				    						</View>
				    					</View>
			    						:null
			    					}
		    				</View>
		    			</View>
		    			<TouchableOpacity style={styles.feedBackButton} onPress={this._submitForm.bind(this)}>
		    				<Text style={styles.submitButton}>提交</Text>
		    			</TouchableOpacity>
		      	</ScrollView>
		    </View>
		);
	}
}

const styles = StyleSheet.create({
	feedBackContainer: {
		flex: 1,
		backgroundColor: "#f6f6f6",
		flexDirection: "column",
	},
	toolbarV: {
		flex: 1,
		justifyContent: 'center',
		alignItems: 'center',
	},
	toolbarT: {
		color: '#ffffff',
		fontWeight: 'bold',
		fontSize: 20
	},
	feedBackButton: {
		width: Dimensions.get('window').width,
		height: ScreenUtils.scaleSize(110),
		borderTopWidth: 1,
		borderColor: "#ebebeb",
		justifyContent: 'center',
		alignItems: "center",
		backgroundColor: '#fff',
		position: "absolute",
		bottom: 0,
		left: 0,
	},
	submitButton: {
		fontSize: ScreenUtils.scaleSize(28),
		color: "#ff4545",
	},
	feedBackWrap: {
		minHeight: (Dimensions.get('window').height - HEADER_HEIGHT-STATUS_BAR_HEIGHT),
		flexDirection: "column",
	},
	feedBackFormWrap: {
		flexDirection: "column",
		paddingBottom: ScreenUtils.scaleSize(140)
	},
	userTipWrap: {
		marginTop: ScreenUtils.scaleSize(10),
		height: ScreenUtils.scaleSize(136),
		justifyContent: 'center',
		borderTopWidth: 1,
		borderBottomWidth: 1,
		borderColor: "#ebebeb",
		backgroundColor: "#fff",
		paddingLeft: ScreenUtils.scaleSize(30),
		paddingRight: ScreenUtils.scaleSize(26),
	},
	userTip: {
		color: "#000",
		fontSize: ScreenUtils.scaleSize(26),
	},
	feedBackForm: {
		height: 'auto',
		flexDirection: "column",
		justifyContent: "space-around",
		backgroundColor: "#fff",
		borderTopWidth: 1,
		borderBottomWidth: 1,
		borderColor: "#ebebeb",
		paddingLeft: ScreenUtils.scaleSize(30),
		paddingRight: ScreenUtils.scaleSize(30),
		marginTop: ScreenUtils.scaleSize(10),
	},
	relaPicsWrap: {
		width: (Dimensions.get('window').width - 2 * ScreenUtils.scaleSize(30)) / 3,
		height: (Dimensions.get('window').width - 2 * ScreenUtils.scaleSize(30)) / 3,
		position: 'relative',
	},
	relaPicsWrapImg: {
		width: (Dimensions.get('window').width - 2 * ScreenUtils.scaleSize(30)) / 3 - 11,
		height: (Dimensions.get('window').width - 2 * ScreenUtils.scaleSize(30)) / 3 - 11,
		marginTop: 10,
	},
	inputAreaWrap: {
		marginTop: ScreenUtils.scaleSize(20),
		height: ScreenUtils.scaleSize(286),
		borderWidth: 1,
		borderColor: '#e5e5e5',
		borderRadius: 5,
		flexDirection: 'column',
	},
	info: {
		fontSize: ScreenUtils.scaleSize(26),
		flex: 1,
		color: "#000",
	},
	relaPics: {
		width: ScreenUtils.scaleSize(80),
		height: ScreenUtils.scaleSize(100),
		alignItems: 'flex-end',
		justifyContent: "center",
		position: 'absolute',
		bottom: ScreenUtils.scaleSize(15),
		right: ScreenUtils.scaleSize(15),
		zIndex: 9999,
	},
	relaPicsImage: {
		height: ScreenUtils.scaleSize(70),
		width: ScreenUtils.scaleSize(70),
	},
	qqNum: {
		marginTop: ScreenUtils.scaleSize(20),
		height: ScreenUtils.scaleSize(60),
		borderWidth: 1,
		borderColor: '#e5e5e5',
		borderRadius: 3,
		fontSize: ScreenUtils.scaleSize(26),
		paddingTop: 5,
		paddingBottom: 5,
	},
	tip: {
		paddingTop: ScreenUtils.scaleSize(20),
		fontSize: ScreenUtils.scaleSize(22),
		color: "#444",
		paddingBottom: ScreenUtils.scaleSize(22),
	},
	modalBackground: {
		backgroundColor: 'rgba(0, 0, 0, 0.5)',
		flex: 1,
		flexDirection: "row",
		alignItems: "flex-end",
	},
	modalContent: {
		flex: 1,
		height: ScreenUtils.scaleSize(224),
		backgroundColor: "#fff",
		flexDirection: "column",
	},
	modalContentWrap: {
		flex: 1,
		flexDirection: "column",
		justifyContent: "center",
		alignItems: "center",
	},
	modalBtn: {
		flex: 1,
		width: Dimensions.get('window').width,
		justifyContent: "center",
		alignItems: "center",
	},
	imageReview: {
		paddingBottom: ScreenUtils.scaleSize(30),
		flexWrap: 'wrap',
		flexDirection: "row",
		alignItems: "stretch",
	}
});